"""
用户管理API端点
===============

处理用户的CRUD操作和管理功能
"""

from typing import List, Dict, Any

from fastapi import APIRouter, Depends, HTTPException, Query, status
from dependency_injector.wiring import inject, Provide

from redfire_framework.core.dependencies import CurrentUserID, AdminUser
from redfire_framework.core.exceptions import UserNotFoundException, UserAlreadyExistsException
from ...schemas.user import (
    UserResponse,
    UserCreateRequest,
    UserUpdateRequest,
    UserListResponse
)
from ...services.user_service import UserService
from ...containers import UserServiceContainer

router = APIRouter()


@router.get("", response_model=UserListResponse)
@inject
async def list_users(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回的记录数"),
    search: str = Query(None, description="搜索关键词"),
    admin_user: Dict[str, Any] = AdminUser,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """获取用户列表（需要管理员权限）"""
    try:
        users, total = await user_service.list_users(
            skip=skip, limit=limit, search=search
        )
        
        user_list = [
            UserResponse(
                id=user.id,
                username=user.username,
                email=user.email,
                is_active=user.is_active,
                created_at=user.created_at
            )
            for user in users
        ]
        
        return UserListResponse(
            users=user_list,
            total=total,
            skip=skip,
            limit=limit
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户列表失败"
        )


@router.post("", response_model=UserResponse)
@inject
async def create_user(
    request: UserCreateRequest,
    admin_user: Dict[str, Any] = AdminUser,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """创建用户（需要管理员权限）"""
    try:
        user = await user_service.create_user(
            username=request.username,
            email=request.email,
            password=request.password,
            full_name=getattr(request, 'full_name', None),
            phone=getattr(request, 'phone', None),
            is_active=request.is_active
        )
        
        return UserResponse(
            id=user.id,
            username=user.username,
            email=user.email,
            is_active=user.is_active,
            created_at=user.created_at
        )
        
    except UserAlreadyExistsException as e:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建用户失败"
        )


@router.get("/{user_id}", response_model=UserResponse)
@inject
async def get_user(
    user_id: str,
    current_user: Dict[str, Any] = CurrentUserID,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """获取用户信息（用户只能查看自己的信息，管理员可以查看所有用户）"""
    # 权限检查：只能查看自己的信息或需要管理员权限
    current_user_id = current_user.get("user_id")
    user_roles = current_user.get("roles", [])
    
    if current_user_id != user_id and "admin" not in user_roles and "super_admin" not in user_roles:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="权限不足：只能访问自己的信息或需要管理员权限"
        )
    
    try:
        user = await user_service.get_user_by_id(user_id)
        
        if not user:
            raise UserNotFoundException(user_id=user_id)
        
        return UserResponse(
            id=user.id,
            username=user.username,
            email=user.email,
            is_active=user.is_active,
            created_at=user.created_at
        )
        
    except UserNotFoundException as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户信息失败"
        )


@router.put("/{user_id}", response_model=UserResponse)
@inject
async def update_user(
    user_id: str,
    request: UserUpdateRequest,
    current_user: Dict[str, Any] = CurrentUserID,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """更新用户信息（用户只能更新自己的信息，管理员可以更新所有用户）"""
    # 权限检查：只能更新自己的信息或需要管理员权限
    current_user_id = current_user.get("user_id")
    user_roles = current_user.get("roles", [])
    
    if current_user_id != user_id and "admin" not in user_roles and "super_admin" not in user_roles:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="权限不足：只能更新自己的信息或需要管理员权限"
        )
    
    try:
        # 构建更新数据
        update_data = {}
        if request.username is not None:
            update_data["username"] = request.username
        if request.email is not None:
            update_data["email"] = request.email
        if hasattr(request, 'full_name') and request.full_name is not None:
            update_data["full_name"] = request.full_name
        if hasattr(request, 'phone') and request.phone is not None:
            update_data["phone"] = request.phone
        if request.is_active is not None:
            # 只有管理员可以修改激活状态
            if current_user.get("user_id") != user_id:
                update_data["is_active"] = request.is_active
        
        user = await user_service.update_user(user_id, **update_data)
        
        if not user:
            raise UserNotFoundException(user_id=user_id)
        
        return UserResponse(
            id=user.id,
            username=user.username,
            email=user.email,
            is_active=user.is_active,
            created_at=user.created_at
        )
        
    except UserNotFoundException as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except UserAlreadyExistsException as e:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新用户信息失败"
        )


@router.delete("/{user_id}")
@inject
async def delete_user(
    user_id: str,
    admin_user: Dict[str, Any] = AdminUser,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """删除用户（需要管理员权限）"""
    try:
        success = await user_service.delete_user(user_id)
        if not success:
            raise UserNotFoundException(user_id=user_id)
        
        return {"message": "用户删除成功"}
        
    except UserNotFoundException as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除用户失败"
        )


@router.post("/{user_id}/activate")
@inject
async def activate_user(
    user_id: str,
    admin_user: Dict[str, Any] = AdminUser,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """激活用户（需要管理员权限）"""
    try:
        success = await user_service.activate_user(user_id)
        if not success:
            raise UserNotFoundException(user_id=user_id)
        
        return {"message": "用户激活成功"}
        
    except UserNotFoundException as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="激活用户失败"
        )


@router.post("/{user_id}/deactivate")
@inject
async def deactivate_user(
    user_id: str,
    admin_user: Dict[str, Any] = AdminUser,
    user_service: UserService = Depends(Provide[UserServiceContainer.user_service])
):
    """停用用户（需要管理员权限）"""
    try:
        success = await user_service.deactivate_user(user_id)
        if not success:
            raise UserNotFoundException(user_id=user_id)
        
        return {"message": "用户停用成功"}
        
    except UserNotFoundException as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="停用用户失败"
        )
